﻿using System;
using System.Linq;
using System.Xml.Linq;

namespace Sonce.Editor.Data
{
    public class EditorDocument
    {
        public static void ImportCircuitXml(string xml)
        {
            //TODO: Parse xml and insert to database
        }

        public static string ExportCircuitXml()
        {
            //Schema: http://zephyr.fe.uni-lj.si/mediawiki/index.php/AndrejKosir/Projekti/Risanje_vezij/XML

            string result = null;
            EditorDataContext db = new EditorDataContext();
            XDocument doc = new XDocument();
            doc.Declaration = new XDeclaration("1.0", "UTF-8", null);
            XElement xroot = new XElement("circuit");

            //Create 'node' tags
            foreach (Node node in db.Nodes)
            {
                XElement xnode = new XElement("node");
                xnode.Add(new XAttribute("nid", node.Id));
                xnode.Add(new XAttribute("x", node.X));
                xnode.Add(new XAttribute("y", node.Y));
                xnode.Add(new XAttribute("label", node.Label ?? ""));
                xroot.Add(xnode);
            }

            //Create 'branch' tags
            foreach (Branch branch in db.Branches)
            {
                XElement xbranch = new XElement("branch");
                xbranch.Add(new XAttribute("bid", branch.Id));
                xbranch.Add(new XAttribute("start", branch.StartNodeId));
                xbranch.Add(new XAttribute("stop", branch.StopNodeId));
                xbranch.Add(new XAttribute("label", branch.Label ?? ""));
                xbranch.Add(new XAttribute("element", branch.ElementId));
                xroot.Add(xbranch);
            }

            //Create 'element' tags
            foreach (Element element in db.Elements)
            {
                XElement xelement = new XElement("element");
                xelement.Add(new XAttribute("eid", element.Id));
                //xelement.Add(new XAttribute("type", element.Prototype)); db.ElementPrototypes.First(e => e.Id == element.ElementPrototypeId);
                xelement.Add(new XAttribute("x", element.X));
                xelement.Add(new XAttribute("y", element.Y));
                xelement.Add(new XAttribute("a", element.Angle));
                xelement.Add(new XAttribute("label", element.Label ?? ""));
                xelement.Add(new XAttribute("value", element.Value ?? ""));
                xroot.Add(xelement);
            }

            doc.Add(xroot);
            result = xroot.ToString();
            return result;
        }
    }
}
